package com.squirrel.michale.search5;

/**
 * @author guanhao 观浩
 * @version 1.0.0.0
 * @createTime 2023/1/18 6:22 PM
 * @company Michale Squirrel
 * @link
 * @description 找出第一个大于目标元素的索引,找出最后一个小于目标元素的索引
 */
public class Example001 {




    public int findFirstGreaterIndex(int[] nums, int target) {

        int left = 0;
        int right = nums.length -1;

        int middle = 0;
        while (left <= right) {
            middle = left + ((right - left) >> 1);
            if (nums[middle] > target) {
                if (nums[middle - 1] <= target) {
                    return middle;
                }else{
                    right = middle - 1;
                }
            } else if (nums[middle] <= target) {
                left = middle + 1;
            }
        }
        return -1;

    }

    public int findLastLessIndex(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;

        int middle = 0;
        while (left <= right) {
            middle = left + ((right - left) >> 1);
            if (nums[middle] >= target) {
                right = middle - 1;
            } else if (nums[middle] < target) {
                if (nums[middle + 1] >= target) {
                    return middle;
                } else {
                    left = middle + 1;
                }
            }
        }
        return -1;
    }


    public static void main(String[] args) {
        int[] nums = new int[]{1, 3, 5, 5, 6, 6, 8, 9, 11};

        Example001 example001 = new Example001();
        System.out.println(example001.findFirstGreaterIndex(nums, 5));
        System.out.println(example001.findLastLessIndex(nums, 5));
    }

}
